<?php
/**
 * Version:4
 * 
 *
 */
class data_rss extends data {
	public function __construct() {
		parent::__construct();
	}
	/**
	 * 统计订阅者的总数
	 *
	 * @param int $rss_id
	 * @param int $number			// 非0时，直接加减该值
	 * @return int
	 */
	public function count_follower ($rss_id, $number=0) {
		$rss_id = intval($rss_id);
		$number	= intval($number);
		
		if ($rss_id) {
			if ($number > 0) {
				$count = $this->db->execute('
					update
						rss
					set
						total_follower = total_follower + "'.$number.'"
					where
						id = "'.$rss_id.'"
				');
			} elseif ($number < 0) {
				$count = $this->db->execute('
					update
						rss
					set
						total_follower = total_follower - "'.abs($number).'"
					where
						id = "'.$rss_id.'"
				');
			} else {
				$count = $this->db->execute('
					update
						rss
					set
						total_follower = (select COUNT(*) AS total from follow_source where source_id="'.$rss_id.'" and source_type="follow_rss")
					where
						id = "'.$rss_id.'"
				');
			}
			return $count;
		} else return false;
	}
	/**
	 * 统计rss的文章总数
	 *
	 * @param int $rss_id
	 * @return int
	 */
	public function count_article ($rss_id) {
		$rss_id = intval($rss_id);
		
		if ($rss_id) {
			$count = $this->db->execute('
				update
					rss
				set
					total_article = (select COUNT(*) AS total from rss_article where rss_id="'.$rss_id.'")
				where
					id = "'.$rss_id.'"
			');
			return $count;
		} else return false;
	}

	/**
	 * 获取一条rss记录的详情
	 *
	 * @param int $id
	 * @return Array
	 */
	public function one ($id) {
		$id		= intval($id);
		if ($id) {
			$execute = $this->db->execute('
				select 
					rss.*,
					rss_link.link		AS link,
					rss_url.url			AS url
				from
					rss, rss_link, rss_url
				where
					rss.id			= "'.$id.'"			and
					rss_link.id		= rss.link_id		and
					rss_url.id		= rss.url_id
			');
			return $execute[0];
		} else return false;
	}
	// rss 的 url 和 link 转换
	/**
	 * 检查URL，返回id，如果没有，则写入后，返回id
	 *
	 * @param String $url
	 * @return int
	 */
	public function url_to_id_if_insert ($url) {
		$url_id = $this->url_to_id($url);
		if ($url_id) {
			return $url_id;
		} else {
			return $this->url_add($url);
		}
	}
	/**
	 * 返回数据库中的url id
	 *
	 * @param String $url
	 * @return int
	 */
	public function url_to_id ($url) {
		$url = url_cut_tail($url);		// 把#号后面的去掉
		if ($url) {
			$url_md5			= md5($url);
			$execute = $this->db->execute('select
												*
											from
												rss_url
											where
												url_md5				= "'.$url_md5.'"
											limit
												1
										');
			if ($execute[0]['id']) {
				return $execute[0]['id'];
			} else return false;
		} else return false;
	}
	/**
	 * url_to_id的别名
	 * url是否存在于数据库中
	 *
	 * @param String $url
	 * @return int
	 */
	public function url_exist ($url) {
		return $this->url_to_id($url);
	}
	/**
	 * 添加一条url记录
	 *
	 * @param String $url
	 * @return int
	 */
	public function url_add ($url) {
		$url = url_cut_tail($url);			// 把#号后面的去掉
		if ($url) {
			$url_md5			= md5($url);
			$insert_id = $this->db->execute('insert into
													rss_url
												set
													url					= "'.$url.'",
													url_md5				= "'.$url_md5.'"
										');
			return $insert_id;
		} else return false;
	}
	/**
	 * 检查link的链接，存在时返回id，不存在时写入数据库并返回id
	 *
	 * @param String $link
	 * @return int
	 */
	public function link_to_id_if_insert ($link) {
		$link_id = $this->link_to_id($link);
		if ($link_id) {
			return $link_id;
		} else {
			return $this->link_add($link);
		}
	}
	/**
	 * 返回数据库中的link id
	 *
	 * @param String $link
	 * @return int
	 */
	public function link_to_id ($link) {
		$link = url_cut_tail($link);				// 把#号后面的去掉
		if ($link) {
			$link_md5			= md5($link);
			$execute = $this->db->execute('select
												*
											from
												rss_link
											where
												link_md5			= "'.$link_md5.'"
											limit
												1
										');
			if ($execute[0]['id']) {
				return $execute[0]['id'];
			} else return false;
		} else return false;
	}
	/**
	 * link_to_id的别名
	 * 	返回数据库中的link id
	 *
	 * @param String $link
	 * @return int
	 */
	public function link_exist ($link) {
		return $this->link_to_id($link);
	}
	/**
	 * 添加一条link记录
	 *
	 * @param String $link
	 * @return int
	 */
	public function link_add ($link) {
		$link = url_cut_tail($link);			// 把#号后面的去掉
		if ($link) {
			$link_md5			= md5($link);
			$insert_id = $this->db->execute('insert into
													rss_link
												set
													link					= "'.$link.'",
													link_md5				= "'.$link_md5.'"
										');
			return $insert_id;
		} else return false;
	}
	/**
	 * 根据rss的基本参数，检查数据库中是否存在、更新、添加，返回id
	 *
	 * @param string $url
	 * @param string $title
	 * @param string $description
	 * @param string $link
	 * @return int
	 */
	public function check_rss_if_insert_or_update ($url, $title, $description, $link) {
		$title			= addslashes(stripcslashes(trim($title)));
		$description	= addslashes(stripcslashes(trim($description)));
		$url			= url_cut_tail($url);
		$link			= url_cut_tail($link);
		
		$url_id		= $this->url_to_id_if_insert($url);
		$link_id	= $this->link_to_id_if_insert($link);
		
		if ($url_id and $title) {
			// 检查是否存在
			$exist = $this->db->execute('
				select 
					* 
				from 
					`rss` 
				where 
					url_id = "'.$url_id.'" 
				limit 
					1
			');
			$exist = $exist[0];
			if ($exist) {			// 存在，检查是否需要更新
				if ($title == addslashes(stripslashes($exist['title'])) and $description == addslashes(stripslashes($exist['description'])) and $link_id == $exist['link_id']) {
					return $exist['id'];		// 不需要更新，返回id
				} else {
					$this->update($exist['id'], $title, $description, $link_id);
					return $exist['id'];		// 更新，返回id
				}
			} else {				// 不存在，添加	返回insert id
				return $this->insert($title, $description, $url_id, $link_id);
			}
		} else return false;
	}
	/**
	 * 向数据库中写入一条rss记录
	 *
	 * @param string $title
	 * @param string $description
	 * @param int $url_id
	 * @param int $link_id
	 * @return int
	 */
	private function insert ($title, $description, $url_id, $link_id) {
		$title			= addslashes(stripcslashes(trim($title)));
		$description	= addslashes(stripcslashes(trim($description)));
		$url_id			= intval($url_id);
		$link_id		= intval($link_id);
		if ($title and $url_id) {
			$insert_id = $this->db->execute('insert into
													`rss`
												set
													title					= "'.$title.'",
													description				= "'.$description.'",
													url_id					= "'.$url_id.'",
													link_id					= "'.$link_id.'",
													last_auto_update_time	= "0000-00-00 00:00:00",
													error_times				= 0,
													total_article			= 0,
													total_follower			= 0
											');
			return $insert_id;
		} else return false;
	}
	/**
	 * 更新一条rss记录
	 *
	 * @param int $id
	 * @param string $title
	 * @param string $description
	 * @param int $link_id
	 * @return int
	 */
	private function update ($id, $title, $description, $link_id) {
		$id				= intval($id);
		$title			= addslashes(stripcslashes(trim($title)));
		$description	= addslashes(stripcslashes(trim($description)));
		$link_id		= intval($link_id);
		
		if ($id and $title) {
			$update = $this->db->execute('update
												`rss`
											set
												title			= "'.$title.'",
												description		= "'.$description.'",
												link_id			= "'.$link_id.'"
											where
												id	= "'.$id.'"
										');
			return $update;
		} else return false;
	}
	/**
	 * 按自动更新的时间列出较早更新的limit条rss记录，超过error_times的记录被忽略（错误次数太多，认为该源消失了）
	 *
	 * @return Array = array (
	 * 		array (id, url),
	 * 		...
	 * )
	 */
	public function all_for_auto_update ($limit=20, $error_times=10) {
		$limit			= intval($limit);
		$error_times 	= intval($error_times);
		$execute = $this->db->execute('
			select 
				rss.id, 
				rss_url.url 
			from 
				`rss`, `rss_url`
			where
				rss.error_times	< "'.$error_times.'"		and
				rss_url.id		= rss.url_id
			order by 
				rss.last_auto_update_time ASC, 
				rss.id ASC
			limit 
				'.$limit.'
		');
		if ($execute) {
			return $execute;
		} else {
			return false;
		}
	}
	/**
	 * 更新rss的基本信息，记录最后更新的时间，把error记录清零
	 *
	 * @param int $id
	 * @param string $title
	 * @param string $description
	 * @param string $link
	 * @param datatime $last_auto_update_time
	 * @return bool
	 */
	public function update_for_auto_update ($id, $title, $description, $link) {
		$id				= intval($id);
		$title			= addslashes(strip_tags(trim($title)));
		$description	= addslashes(strip_tags(trim($description)));
		$link			= url_cut_tail($link);
		$link_id		= $this->link_to_id_if_insert($link);
		
		if ($id and $title) {
			$update = $this->db->execute('
				update
					`rss`
				set
					title					= "'.$title.'",
					description				= "'.$description.'",
					link_id					= "'.$link_id.'",
					last_auto_update_time	= "'.date('Y-m-d H:i:s').'",
					error_times				= "0"
				where
					id = "'.$id.'"
			');
			return $update;
		}
	}
	/**
	 * 更新时间，记录error次数
	 *
	 * @param int $id
	 * @return int
	 */
	public function update_error ($id) {
		$id = intval($id);
		if ($id) {
			$update = $this->db->execute('
				update
					`rss`
				set
					last_auto_update_time	= "'.date('Y-m-d H:i:s').'",
					error_times				= error_times + 1
				where
					id = "'.$id.'"
			');
			return $update;
		} else return false;
	}
	
	public function auto_run () {
		$remote_file 				= new remote_file();
		$data_rss_article			= new data_rss_article();
		
		// 读出所有rss，错误次数太多的就放弃了
		$rss = $this->all_for_auto_update(20, 10);			// 返回的数据格式： array (array (id, url), ...)
		if (is_array($rss)) {
			foreach ($rss as $r) {
				// 解析xml文件
				$parser = $remote_file->parse_xml($r['url']);		// 返回的数据格式： array ('title', 'link', 'description', 'items'=>array(array('title', 'link', 'description', 'content', 'pubdate'), ...))
				if ($parser) {
					// 检查数据库并更新rss记录
					$this->update_for_auto_update($r['id'], $parser['title'], $parser['description'], $parser['link']);
					// 逐条处理items
					if (is_array($parser['items'])) {
						foreach ($parser['items'] as $item) {
							// 检查并写入/更新article, 检查并写入rss_article
							$data_rss_article->update_or_add($r['id'], $item['link'], $item['title'], $item['description'], $item['content'], $item['pubdate']);
						}
					}
				} else {
					// 未能获得xml文件，记录错误，也记录一下更新时间
					$this->update_error($r['id']);
				}
				// 更新rss中的文章总数
				$this->count_article($r['id']);
			}
		}
	}
	
	// 以下暂时没用到 ------------------------------------------------------------------------------------------------------------------------------------------
	
	
	public function ls_friend_followed ($uid, $page=1, $limit=10) {
		$uid	= intval($uid);
		$page	= intval($page);
		$page	= ($page) ? $page : 1;
		$limit 	= intval($limit);
		$limit 	= ($limit) ? $limit : 1;
		
		if ($uid and $page and $limit) {
			$execute = $this->db->execute('select
												rss.id					AS id,
												rss.title				AS title,
												rss.total_article		AS total_article,
												rss.total_follower		AS total_follower
											from
												follow_source, friend, rss
											where
												friend.user_id					= "'.$uid.'"					and
												follow_source.user_id			= friend.friend_id				and
												follow_source.source_type		= "follow_rss"					and
												rss.id							= follow_source.source_id
											group by
												follow_source.source_id
											order by
												rss.total_follower DESC,
												rss.total_article DESC,
												rss.id DESC
											limit
												'.(($page-1)*$limit).', '.$limit.'	
										');
			return $execute;
		} else return false;
	}
	
	public function ls_hot_followed ($uid, $page=1, $limit=10) {
		$uid	= intval($uid);
		$page	= intval($page);
		$page	= ($page) ? $page : 1;
		$limit 	= intval($limit);
		$limit 	= ($limit) ? $limit : 1;
		
		if ($uid and $page and $limit) {
			$execute = $this->db->execute('select
												rss.id					AS id,
												rss.title				AS title,
												rss.total_article		AS total_article,
												rss.total_follower		AS total_follower,
												rss_link.link			AS link
											from
												rss, rss_link
											where
												rss_link.id		= rss.link_id
											order by
												rss.total_follower DESC,
												rss.total_article DESC,
												rss.id DESC
											limit
												'.(($page-1)*$limit).', '.$limit.'	
										');
			return $execute;
		} else return false;
	}
}
?>